function [dataDiff] = diff_unwrap(data, bitNum, threshold) %#codegen
%DIFF_UNWRAP 对有翻转的数据进行差分
%
% Input Arguments:
% data: m*n double矩阵，待差分数据
% bitNum: 标量或1*n向量，各列数据位数，0表示不作翻转，默认为16
% threshold: 标量，翻转阈值，差分数据绝对值超过数据类型值域的threshold倍即判为翻转，无单位，默认为0.5
%
% Output Arguments:
% diff: m-1*n矩阵，按列差分并进行翻转处理后的数据

if nargin < 3
    threshold = 0.5;
end
if nargin < 2
    bitNum = 16;
end

assert((threshold<=1) && (threshold>=0));

n = size(data, 2);
if isscalar(bitNum)
    bitNumFull = ones(1, n) * bitNum(1, 1);
else
    bitNumFull = bitNum;
end
dataDiff = diff(data);
for i=1:n
    if bitNumFull(1, i) > 0
        range = 2^bitNumFull(1, i);
        indP = find(dataDiff(:, i) > range*threshold);
        indN = find(dataDiff(:, i) < -range*threshold);
        dataDiff(indP, i) = dataDiff(indP, i) - range;
        dataDiff(indN, i) = dataDiff(indN, i) + range;
    end
end
end